package com.nq.service.impl;

/**

 * 开发者----股牛网络

 * 联系TG：gncms

 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.nq.dao.SiteAdminMapper;
import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;

import com.nq.common.ServerResponse;

import com.nq.dao.stock.StUserLevelMapper;
import com.nq.pojo.SiteAdmin;

import com.nq.pojo.UserRecharge;

import com.nq.service.IAgentUserService;

import com.nq.service.ISiteAdminService;

import com.nq.service.IStockService;

import com.nq.service.IUserPositionService;

import com.nq.service.IUserRechargeService;

import com.nq.service.IUserService;

import com.nq.service.IUserWithdrawService;

import com.nq.stock.entity.StUserLevel;
import com.nq.utils.PropertiesUtil;

import com.nq.utils.SymmetricCryptoUtil;
import com.nq.utils.redis.JsonUtil;
import com.nq.utils.redis.RedisConst;
import com.nq.utils.redis.RedisShardedPoolUtils;


import com.nq.vo.admin.AdminCountVO;

import java.math.BigDecimal;

import java.util.Date;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


@Service("iSiteAdminServiceImpl")

public class SiteAdminServiceImpl implements ISiteAdminService {
    private static final Logger log = LoggerFactory.getLogger(SiteAdminServiceImpl.class);


    @Autowired
    SiteAdminMapper siteAdminMapper;
    @Autowired
    IUserRechargeService iUserRechargeService;
    @Autowired
    IUserService iUserService;
    @Autowired
    IUserWithdrawService iUserWithdrawService;
    @Autowired
    IUserPositionService iUserPositionService;
    @Autowired
    IAgentUserService iAgentUserService;
    @Autowired
    IStockService iStockService;
    @Resource
    private StUserLevelMapper userLevelMapper;


    public ServerResponse login(String adminPhone, String adminPwd, String verifyCode, HttpServletRequest request) {

        if (StringUtils.isBlank(verifyCode)) {

            return ServerResponse.createByErrorMsg("The verification code cannot be empty.");

        }

        String original = (String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");

        /*if (!verifyCode.equalsIgnoreCase(original)) {

            return ServerResponse.createByErrorMsg("验证码错误");

        }*/


        if (StringUtils.isBlank(adminPhone) || StringUtils.isBlank(adminPwd)) {

            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");

        }

        adminPwd = SymmetricCryptoUtil.encryptPassword(adminPwd);
        SiteAdmin siteAdmin = this.siteAdminMapper.login(adminPhone, adminPwd);
//        SiteAdmin siteAdmin = (SiteAdmin) siteAdminMapper.selectOne(new QueryWrapper<SiteAdmin>().eq("admin_phone", adminPhone).eq("admin_pwd", adminPwd));

        if (siteAdmin == null) {

            return ServerResponse.createByErrorMsg("Incorrect account password.");

        }


        if (siteAdmin.getIsLock().intValue() == 1) {

            return ServerResponse.createByErrorMsg("Account Locked");

        }


        siteAdmin.setAdminPwd(null);
        HttpSession httpSession = request.getSession();
        String token = RedisConst.getAdminRedisKey(httpSession.getId());
        RedisShardedPoolUtils.set(token, JsonUtil.obj2String(siteAdmin));
        siteAdmin.setToken(token);
        return ServerResponse.createBySuccess(siteAdmin);

    }


    public ServerResponse<PageInfo> listByAdmin(String adminName, String adminPhone, HttpServletRequest request, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);


        String superAdmin = PropertiesUtil.getProperty("admin.super.name");


        List<SiteAdmin> siteAdmins = this.siteAdminMapper.listByAdmin(adminName, adminPhone, superAdmin);


        PageInfo<SiteAdmin> pageInfo = new PageInfo<>(siteAdmins);

        return ServerResponse.createBySuccess(pageInfo);

    }


    public ServerResponse authCharge(String token, Integer state, String orderSn) {

        if (StringUtils.isBlank(token) || state == null || StringUtils.isBlank(orderSn)) {

            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");

        }


        String redis_token = RedisShardedPoolUtils.get(token);

        if (StringUtils.isBlank(redis_token)) {

            return ServerResponse.createByErrorMsg("Token error or expired");

        }


        ServerResponse serverResponse = this.iUserRechargeService.findUserRechargeByOrderSn(orderSn);

        if (!serverResponse.isSuccess()) {

            return serverResponse;

        }


        UserRecharge userRecharge = (UserRecharge) serverResponse.getData();

        ServerResponse returnResponse = null;

        try {

            if (state.intValue() == 1) {

                returnResponse = this.iUserRechargeService.chargeSuccess(userRecharge);

            } else if (state.intValue() == 2) {

                returnResponse = this.iUserRechargeService.chargeFail(userRecharge);

            } else if (state.intValue() == 3) {

                returnResponse = this.iUserRechargeService.chargeCancel(userRecharge);

            } else {

                return ServerResponse.createByErrorMsg("The state is not right. Don't deal with it.");

            }

        } catch (Exception e) {

            log.error("email 审核入金状态出错，错误信息 = {}", e);

        }

        return returnResponse;

    }


    public ServerResponse updateLock(Integer adminId) {

        SiteAdmin siteAdmin = this.siteAdminMapper.selectByPrimaryKey(adminId);

        if (siteAdmin == null) {

            return ServerResponse.createByErrorMsg("Administrator does not exist");

        }

        if (siteAdmin.getIsLock().intValue() == 0) {

            siteAdmin.setIsLock(Integer.valueOf(1));

        } else {

            siteAdmin.setIsLock(Integer.valueOf(0));

        }

        int updateCount = this.siteAdminMapper.updateByPrimaryKeySelective(siteAdmin);

        if (updateCount > 0) {

            return ServerResponse.createBySuccessMsg("Modified Successfully");

        }

        return ServerResponse.createByErrorMsg("Modification Failed");

    }


    public ServerResponse add(SiteAdmin siteAdmin) {

        if (StringUtils.isBlank(siteAdmin.getAdminName()) ||

                StringUtils.isBlank(siteAdmin.getAdminPhone()) ||

                StringUtils.isBlank(siteAdmin.getAdminPwd()) || siteAdmin

                .getIsLock() == null) {

            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");

        }


        SiteAdmin siteAdmin1 = this.siteAdminMapper.findAdminByName(siteAdmin.getAdminName());

        if (siteAdmin1 != null) {

            return ServerResponse.createByErrorMsg("The management name exists.");

        }

        SiteAdmin siteAdmin2 = this.siteAdminMapper.findAdminByPhone(siteAdmin.getAdminPhone());

        if (siteAdmin2 != null) {

            return ServerResponse.createByErrorMsg("The mobile phone number exists.");

        }


        SiteAdmin dbadmin = new SiteAdmin();

        dbadmin.setAdminName(siteAdmin.getAdminName());

        dbadmin.setAdminPhone(siteAdmin.getAdminPhone());

        dbadmin.setAdminPwd(SymmetricCryptoUtil.encryptPassword(siteAdmin.getAdminPwd()));

        dbadmin.setIsLock(siteAdmin.getIsLock());

        dbadmin.setAddTime(new Date());


        int insertCount = this.siteAdminMapper.insert(dbadmin);

        if (insertCount > 0) {

            return ServerResponse.createBySuccessMsg("Added successfully");

        }

        return ServerResponse.createByErrorMsg("Failed to add");

    }


    public ServerResponse update(SiteAdmin siteAdmin) {

        if (siteAdmin.getId() == null) {

            return ServerResponse.createByErrorMsg("Modify the id not empty.");

        }

        siteAdmin.setAdminPwd(SymmetricCryptoUtil.encryptPassword(siteAdmin.getAdminPwd()));
        int updateCount = this.siteAdminMapper.updateByPrimaryKeySelective(siteAdmin);

        if (updateCount > 0) {

            return ServerResponse.createBySuccessMsg("Successful modification");

        }

        return ServerResponse.createByErrorMsg("Modification Failed");

    }

    public ServerResponse deleteAdmin(Integer adminId) {

        if (adminId == null) {
            return ServerResponse.createByErrorMsg("Deleted id cannot be empty.");
        }
        int updateCount = this.siteAdminMapper.deleteByPrimaryKey(adminId);

        if (updateCount > 0) {

            return ServerResponse.createBySuccessMsg("Deleted successfully");

        }

        return ServerResponse.createByErrorMsg("Failed to delete");

    }

    @Override
    public ServerResponse userLevelList(int pageNum, int pageSize, HttpServletRequest request) {
        List<StUserLevel> userLevels = userLevelMapper.selectList(new QueryWrapper<>());
        return ServerResponse.createBySuccess(userLevels);
    }

    @Override
    public ServerResponse updateOrAddUserLevel(Integer id, String name, Integer level, String amount,String firstFee, String secondFee, String thirdFee, HttpServletRequest request) {

        if (null == id) {
            StUserLevel userLevel = new StUserLevel();
            userLevel.setAmount(new BigDecimal(amount));
            userLevel.setName(name);
            userLevel.setLevel(level);
            userLevel.setFirstFee(new BigDecimal(firstFee));
            userLevel.setSecondFee(new BigDecimal(secondFee));
            userLevel.setThirdFee(new BigDecimal(thirdFee));
            userLevel.setCreateTime(new Date());
            userLevelMapper.insert(userLevel);
        }else {
            StUserLevel userLevel = userLevelMapper.selectById(id);
            userLevel.setAmount(new BigDecimal(amount));
            userLevel.setName(name);
            userLevel.setLevel(level);
            userLevel.setFirstFee(new BigDecimal(firstFee));
            userLevel.setSecondFee(new BigDecimal(secondFee));
            userLevel.setThirdFee(new BigDecimal(thirdFee));
            userLevelMapper.updateById(userLevel);
        }

        return ServerResponse.createBySuccess("操作成功");
    }

    @Override
    public ServerResponse delUserLevel(Integer id, HttpServletRequest request) {
        int i = userLevelMapper.deleteById(id);
        return ServerResponse.createBySuccess("操作成功");
    }


    public SiteAdmin findAdminByName(String name) {
        return this.siteAdminMapper.findAdminByName(name);
    }


    public SiteAdmin findAdminByPhone(String phone) {
        return this.siteAdminMapper.findAdminByPhone(phone);
    }


    public ServerResponse count() {

        AdminCountVO adminCountVO = new AdminCountVO();


        int user_sp_num = this.iUserService.CountUserSize(Integer.valueOf(0));
        int user_moni_num = this.iUserService.CountUserSize(Integer.valueOf(1));
        adminCountVO.setUser_sp_num(user_sp_num);
        adminCountVO.setUser_moni_num(user_moni_num);


        int agent_num = this.iAgentUserService.CountAgentNum();
        adminCountVO.setAgent_num(agent_num);


        BigDecimal user_sp_sum_amt = this.iUserService.CountUserAmt(Integer.valueOf(0));
        BigDecimal user_sp_sum_enable = this.iUserService.CountEnableAmt(Integer.valueOf(0));

        adminCountVO.setUser_sp_sum_amt(user_sp_sum_amt);
        adminCountVO.setUser_sp_sum_enable(user_sp_sum_enable);

        //累计充值金额
        BigDecimal charge_sum_amt = this.iUserRechargeService.CountChargeSumAmt(Integer.valueOf(1));
        //今日充值金额
        BigDecimal charge_today_sum_amt = this.iUserRechargeService.CountTotalRechargeAmountByTime(Integer.valueOf(1));

        //累计提现金额
        BigDecimal sp_withdraw_sum_amt_success = this.iUserWithdrawService.CountSpWithSumAmtByState(Integer.valueOf(1));
        //今日提现金额
        BigDecimal sp_withdraw_sum_today_amt_success = this.iUserWithdrawService.CountSpWithSumAmTodaytByState(Integer.valueOf(1));
        // 审核中的提现金额
        BigDecimal sp_withdraw_sum_amt_apply = this.iUserWithdrawService.CountSpWithSumAmtByState(Integer.valueOf(0));

        adminCountVO.setCharge_sum_amt(charge_sum_amt);
        adminCountVO.setCharge_today_sum_amt(charge_today_sum_amt);

        adminCountVO.setSp_withdraw_sum_amt_success(sp_withdraw_sum_amt_success);
        adminCountVO.setSp_withdraw_sum_today_amt_success(sp_withdraw_sum_today_amt_success);

        adminCountVO.setSp_withdraw_sum_amt_apply(sp_withdraw_sum_amt_apply);


        int sp_position_num = this.iUserPositionService.CountPositionNum(Integer.valueOf(1), Integer.valueOf(0));

        int sp_pc_position_num = this.iUserPositionService.CountPositionNum(Integer.valueOf(2), Integer.valueOf(0));

        adminCountVO.setSp_position_num(sp_position_num);

        adminCountVO.setSp_pc_position_num(sp_pc_position_num);

        // 涨跌幅
        BigDecimal sp_profit_and_lose = this.iUserPositionService.CountPositionProfitAndLose();
        // 总的涨跌幅
        BigDecimal sp_all_profit_and_lose = this.iUserPositionService.CountPositionAllProfitAndLose();

        adminCountVO.setSp_profit_and_lose(sp_profit_and_lose);
        adminCountVO.setSp_all_profit_and_lose(sp_all_profit_and_lose);

        // 股票总数
        int stock_num = this.iStockService.CountStockNum();

        // 股票显示总数
        int stock_show_num = this.iStockService.CountShowNum(Integer.valueOf(0));
        // 股票未锁定总数
        int stock_un_lock_num = this.iStockService.CountUnLockNum(Integer.valueOf(0));

        adminCountVO.setStock_num(stock_num);

        adminCountVO.setStock_show_num(stock_show_num);

        adminCountVO.setStock_un_lock_num(stock_un_lock_num);

        return ServerResponse.createBySuccess(adminCountVO);
    }


    public static void main(String[] args) {
        System.out.println(RedisShardedPoolUtils.   get("1"));
        System.out.println(RedisShardedPoolUtils.get("2"));
    }

}
